package net.easyjava.third.db.nosql.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


public class SerializeUtil {

    private static Logger logger = LoggerFactory.getLogger(SerializeUtil.class);

    /**
     * 序列化对象
     * @param object
     * @return
     * @throws IOException
     */
    public static byte[] serialize(Object object) throws IOException {
        if(object == null){
            throw new NullPointerException("object can't be null");
        }
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        oos.writeObject(object);
        byte[] bytes = baos.toByteArray();
        baos.close();
        oos.close();
        return bytes;
    }

    /**
     * 反序列化对象
     * @param bytes
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Object unserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        if (bytes == null) {
            throw new NullPointerException("bytes can't be null");
        }
        Object object = null;
        ByteArrayInputStream bais = null;
        bais = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bais);
        object = ois.readObject();
        bais.close();
        ois.close();
        return object;
    }

    /**
     * =================== serializeList===========================
     *
     * @param list
     * @return
     * @throws Exception
     */
    public static byte[] serializeList(List list) throws IOException {
        if(list == null){
            throw new NullPointerException("list can't be null");
        }
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        for (Object object : list)
            oos.writeObject(object);
        oos.writeObject(null);////解决EOF的关键，加入一个空的对象
        byte[] bytes = baos.toByteArray();
        baos.close();
        oos.close();
        return bytes;
    }

    /**
     * 反序列化list
     * @param bytes
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static List unserializeList(byte[] bytes) throws IOException, ClassNotFoundException {
        List list = new ArrayList();
        if (bytes == null) {
            throw new NullPointerException("bytes can't be null");
        }
        ByteArrayInputStream bais = null;
        bais = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bais);
        Object object = null;
        while ((object = ois.readObject()) != null) {
            list.add(object);
        }
        bais.close();
        ois.close();
        return list;

    }


}
